// lib/pages/bottom_integral_discount.dart
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_deer/res/colors.dart';
import 'package:flutter_deer/res/dimens.dart';
import 'package:flutter_deer/util/input_formatter/money_util.dart';

// 定义常量，提高代码可维护性
const double kDefaultPadding = 10.0;
const double kBorderRadius = 16.0;

class BottomIntegralDiscount extends StatefulWidget {
  final Function() onCancel;
  final Function(String) onConfirm;
  final String myIntegral;
  final String integralTips;
  final String maxDiscount;
  final String useDiscount;
  final String integralPrice;

  const BottomIntegralDiscount({
    Key? key,
    required this.onCancel,
    required this.onConfirm,
    required this.myIntegral,
    required this.integralTips,
    required this.maxDiscount,
    required this.useDiscount,
    required this.integralPrice,
  }) : super(key: key);

  @override
  State<BottomIntegralDiscount> createState() => _BottomIntegralDiscountState();
}

class _BottomIntegralDiscountState extends State<BottomIntegralDiscount> {
  late TextEditingController _inputController;
  String _calculatedDiscount = '0.00';
  int _maxIntegral = 0;

  @override
  void initState() {
    super.initState();
    // 解析最大积分值
    _maxIntegral = _parseIntegral(widget.maxDiscount);

    // 初始化输入控制器并设置默认值为最大积分
    _inputController = TextEditingController(text: widget.useDiscount);
    _inputController.addListener(_onTextChanged);

    // 初始化计算结果
    _calculatedDiscount = _calculateDiscount( _parseIntegral(widget.useDiscount));
  }

  @override
  void dispose() {
    _inputController.removeListener(_onTextChanged);
    _inputController.dispose();
    super.dispose();
  }

  // 解析积分字符串，提取数字部分
  int _parseIntegral(String integralStr) {
    final RegExp regex = RegExp(r'(\d+)');
    final Match? match = regex.firstMatch(integralStr);
    if (match != null) {
      return int.tryParse(match.group(1) ?? '0') ?? 0;
    }
    return 0;
  }

  // 根据积分计算抵扣金额
  String _calculateDiscount(int integral) {
    // 这里可以根据业务逻辑计算抵扣金额
    // 示例：假设100积分=1元
    return integral.toString().multiply(widget.integralPrice);
  }

  // 输入框文本变化监听
  void _onTextChanged() {
    final String text = _inputController.text;
    if (text.isEmpty) {
      setState(() {
        _calculatedDiscount = '0.00';
      });
      return;
    }

    final int? integral = int.tryParse(text);
    if (integral == null) return;

    // 限制输入不超过最大积分
    if (integral > _maxIntegral) {
      // 截断到最大值
      _inputController.value = TextEditingValue(
        text: _maxIntegral.toString(),
        selection: TextSelection.collapsed(offset: _maxIntegral.toString().length),
      );
      return;
    }

    setState(() {
      _calculatedDiscount = _calculateDiscount(integral);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Dialog(
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(kBorderRadius),
      ),
      child: IntrinsicHeight(
        // 让高度自适应内容
        child: Container(
          width: 500,
          // height: 350,
          padding: const EdgeInsets.all(kDefaultPadding),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(kBorderRadius),
            color: Colours.white,
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch, // 让子组件宽度撑满父容器
            mainAxisSize: MainAxisSize.min, // 让 Column 高度自适应
            children: [
              _buildHeader(context),
              const SizedBox(height: kDefaultPadding),
              _buildIntegralTips(),
              const SizedBox(height: kDefaultPadding),
              _buildMyIntegral('我的积分', widget.myIntegral),
              _buildMyIntegral('本单抵扣最高可用', widget.maxDiscount),
              const SizedBox(height: kDefaultPadding),
              _buildInputAndButtons(),
            ],
          ),
        ),
      ),
    );
  }

  // 构建头部标题和关闭按钮
  Widget _buildHeader(BuildContext context) {
    return Row(
      children: [
        Expanded(
          child: Text(
            '积分',
            textAlign: TextAlign.center,
            style: TextStyle(
              color: const Color(0xFF333333),
              fontSize: 17,
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
        IconButton(
          icon: const Icon(Icons.close),
          onPressed: () {
            Navigator.pop(context);
          },
        ),
      ],
    );
  }

  // 构建积分提示信息
  Widget _buildIntegralTips() {
    return Container(
      padding: const EdgeInsets.all(10),
      decoration: BoxDecoration(
        color: const Color(0xFFFFF8F5),
        borderRadius: BorderRadius.circular(4),
      ),
      child: Row(
        children: [
          const Icon(Icons.info_outline, color: Colours.redFF6634),
          const SizedBox(width: 8),
          Flexible(
              // 使用 Flexible 让 Text 组件在空间不足时自动换行
              child: Text(
            widget.integralTips,
            style: const TextStyle(
              color: Color(0xFFFF6634),
              fontSize: Dimens.font_sp16,
            ),
          )),
        ],
      ),
    );
  }

  // 构建我的积分信息
  Widget _buildMyIntegral(String title, String integral) {
    return Row(children: [
      Text('\t\t\t$title：', style: const TextStyle(fontSize: Dimens.font_sp16)),
      Text(integral, style: const TextStyle(fontSize: Dimens.font_sp16, color: Colours.redFF6634)),
    ]);
  }

  // 构建输入积分和抵扣金额以及按钮
  Widget _buildInputAndButtons() {
    return Container(
      padding: const EdgeInsets.all(10),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(10),
      ),
      child: Column(
        children: [
          Container(
            decoration: BoxDecoration(
              border: Border.all(
                color: const Color(0xFFCCCCCC),
              ),
              borderRadius: BorderRadius.circular(5),
            ),
            child: Row(
              children: [
                Expanded(
                  child: TextField(
                    controller: _inputController,
                    decoration: const InputDecoration(
                      hintText: '请输入需要抵扣的积分',
                      border: InputBorder.none,
                      contentPadding: EdgeInsets.symmetric(
                        horizontal: 15,
                      ),
                    ),
                    maxLines: 1,
                    keyboardType: TextInputType.number,
                    inputFormatters: [
                      FilteringTextInputFormatter.digitsOnly, // 只允许输入数字
                    ],
                  ),
                ),
                Text(
                  '可抵扣 $_calculatedDiscount 元',
                  style: const TextStyle(
                    color: Color(0xFF333333),
                    fontSize: 14,
                  ),
                ),
                const SizedBox(width: 12),
              ],
            ),
          ),
          const SizedBox(height: 15),
          // 取消和确定按钮
          Row(
            children: [
              Expanded(
                child: OutlinedButton(
                  onPressed: widget.onCancel,
                  style: OutlinedButton.styleFrom(
                    side: const BorderSide(
                      color: Color(0xFF333333),
                      width: 1,
                    ),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(5),
                    ),
                  ),
                  child: const Text(
                    '不使用积分',
                    style: TextStyle(
                      color: Color(0xFF333333),
                      fontSize: 18,
                    ),
                  ),
                ),
              ),
              const SizedBox(width: 15),
              Expanded(
                child: ElevatedButton(
                  onPressed: () => widget.onConfirm(_inputController.text),
                  style: ElevatedButton.styleFrom(
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(5),
                    ),
                  ),
                  child: const Text(
                    '确定',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 18,
                    ),
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }
}
